package com.example.redis.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;

/**
 * @author xianxin
 * @since 2020/8/21
 */
@Slf4j
public class DemoRedisCallback implements RedisCallback<Boolean> {

    private String lockKey;
    private String lockValue;
    private long lockExpireTime;

    public void setLockKey(String lockKey) {
        this.lockKey = lockKey;
    }

    public void setLockValue(String lockValue) {
        this.lockValue = lockValue;
    }

    public void setLockExpireTime(long seconds) {
        this.lockExpireTime = seconds;
    }

    @Override
    public Boolean doInRedis(RedisConnection connection) throws DataAccessException {

//        Properties properties = connection.info();
//        log.info("{}", properties);

        byte[] k = this.lockKey.getBytes();
        byte[] v = this.lockValue.getBytes();

        // setNx原子性操作,防止同一把锁在同一时间可能被不同线程获取到
        Boolean f1 = connection.setNX(k, v);
        log.info("锁[{}]: {}", this.lockKey, f1);
        if (f1) {
            Boolean f2 = connection.expire(k, this.lockExpireTime);
            log.info("锁[{}]设置超期自动解锁时间({}): {}s", this.lockKey, f2, this.lockExpireTime);
        }

        return f1;
    }
}
